//
//  ThreadViewController.m
//  niminban
//
//  Created by zhouteng on 16/10/6.
//  Copyright © 2016年 zhouteng. All rights reserved.
//

#import "ThreadViewController.h"
#import "UIViewController+MMDrawerController.h"
#import "AFNetworking.h"
#import "URLS.h"
#import "MJExtension.h"
#import "TitleView.h"
#import "Reply.h"
#import "NSString+HTML.h"
#import "MMDrawerBarButtonItem.h"
#import "Masonry.h"
#import "COLORS.h"

#define WIDTH self.view.bounds.size.width
#define HEIGHT self.view.bounds.size.height

@interface ThreadViewController ()

@end

@implementation ThreadViewController
static NSString *CellIdentifier = @"cell";

-(instancetype)init{
    self=[super init];
    if(self){
        lastItemReached = NO;
        isLoading =NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
    
    [self update];
}

-(void)viewDidAppear:(BOOL)animated{

}


-(void)add{
    NSLog(@"add");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)refresh{
    _page = 1;
    [self getThread:YES];
}

-(void)reloadData{
    [self.tableView reloadData];
}

-(void)initView{
    UIBarButtonItem *addBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add)];
    
    self.view.backgroundColor = GRAY_COLOR;
    
    self.navigationItem.rightBarButtonItem = addBtn;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    self.tableView.backgroundColor = GRAY_COLOR;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.allowsSelection = NO;
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 44.0;
    
    [self.tableView registerClass:[TitleView class] forCellReuseIdentifier:CellIdentifier];
    
    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TitleView *cell;
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[TitleView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    [self setCell:cell index:indexPath.row];
    
    if (!lastItemReached &&!isLoading && indexPath.row == [self getCount] - 1)
    {
        [self launchReload];
    }
    
    return cell;
}

-(void)launchReload{
    _page += 1;
    isLoading = YES;
    [self getThread:NO];
}

-(void)setCell:(TitleView *)cell index:(NSInteger)index{
    if(index == 0){
        Thread *thread =_arrThread[index];
        cell.lblId.text = thread.userid;
        cell.lblNo.text = thread.id;
        cell.lblTime.text = thread.now;
        //cell.lblReplyNum.text = _thread.replyCount;
        
        NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[thread.content dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        cell.txtContent.attributedText = attrStr;
    }else{
        Reply *reply = _arrThread[index];
        cell.lblId.text = reply.userid;
        cell.lblNo.text = reply.id;
        cell.lblTime.text = reply.now;
        cell.lblReplyNum.text = nil;

        NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[reply.content dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        cell.txtContent.attributedText = attrStr;
    }
}

-(NSInteger)getCount{
    if(_arrThread){
        return [_arrThread count];
    }
    
    return 0;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self getCount];
}


-(void)getThread:(BOOL)refresh{
    NSString *URLString = GET_THREAD;
    NSLog(GET_THREAD);
    AFHTTPSessionManager *magager = [AFHTTPSessionManager manager];
    
    magager.responseSerializer = [AFJSONResponseSerializer serializer  ];
    
    NSDictionary *parameters = @{@"id":_id,@"page":[NSNumber numberWithLong: _page]};
    
    [magager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if(refresh){
            [self.refreshControl endRefreshing];
            Thread *thread = [Thread mj_objectWithKeyValues:responseObject];
            _arrThread = [[NSMutableArray alloc]init];
            [_arrThread addObject:thread];
            [_arrThread addObjectsFromArray:thread.replys];
        }else{
            isLoading = NO;
            [self.refreshControl endRefreshing];
            Thread *thread = [Thread mj_objectWithKeyValues:responseObject];
            if(thread.replys.count > 0){
                [_arrThread addObjectsFromArray:thread.replys];
            }else{
                lastItemReached = YES;
            }
            
        }
        
        
        NSLog(@"%@",_arrThread);
        
        [self reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(refresh){
            [self.refreshControl endRefreshing];
        }else{
            isLoading = NO;
        }
        NSLog(@"error");
    }];
}

-(void)update{
    [self.refreshControl beginRefreshing];
    [self.tableView setContentOffset:CGPointMake(0, -self.refreshControl.frame.size.height) animated:YES];
    [self getThread:YES];
}

-(void)update:(NSString *)id page:(NSInteger)page{
    _id = id;
    _page = page;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
